package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.constants.WemediaConstants;
import com.heima.common.exception.CustomException;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.WmNewsDto;
import com.heima.model.wemedia.dtos.WmNewsPageReqDto;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmNewsMaterial;
import com.heima.utils.common.WmThreadLocalUtil;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.service.WmNewsAutoScanService;
import com.heima.wemedia.service.WmNewsService;
import com.heima.wemedia.service.WmNewsTaskService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Transactional
public class WmNewsServiceImpl extends ServiceImpl<WmNewsMapper, WmNews> implements WmNewsService {

    @Autowired
    private WmNewsMaterialMapper wmNewsMaterialMapper;

    @Autowired
    private WmMaterialMapper wmMaterialMapper;

    @Autowired
    private WmNewsAutoScanService wmNewsAutoScanService;

    @Autowired
    private WmNewsTaskService wmNewsTaskService;

    /**
     * 根据条件分页查询文章的列表数据
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult findAll(WmNewsPageReqDto dto) {
        //1. 校验参数 参数不合法返回501
        if(null == dto){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        dto.checkParam();//校验和修正分页数据

        //2. 设置查询的条件
        LambdaQueryWrapper<WmNews> queryWrapper = new LambdaQueryWrapper<>();
        //状态过滤
        if(null != dto.getStatus()){
            queryWrapper.eq(WmNews::getStatus, dto.getStatus());
        }

        //创建时间过滤
        if(null != dto.getBeginPubDate() && null != dto.getEndPubDate()){
            queryWrapper.between(WmNews::getCreatedTime, dto.getBeginPubDate(), dto.getEndPubDate());
        }

        //频道过滤
        if(null != dto.getChannelId()){
            queryWrapper.eq(WmNews::getChannelId, dto.getChannelId());
        }

        //关键字搜索
        if(StringUtils.isNotEmpty(dto.getKeyword())){
            queryWrapper.like(WmNews::getTitle, dto.getKeyword());
        }

        //3. 设置排序规则
        queryWrapper.orderByDesc(WmNews::getCreatedTime);

        //4. 设置分页参数
        IPage page = new Page(dto.getPage(), dto.getSize());

        //5. 分页查询
        page(page, queryWrapper);

        //6. 封装结果
        PageResponseResult responseResult = new PageResponseResult();

        responseResult.setCurrentPage(dto.getPage());
        responseResult.setSize(dto.getSize());
        responseResult.setTotal((int) page.getTotal());
        responseResult.setData(page.getRecords());

        return responseResult;
    }

    /**
     * 保存或者更新文章数据
     * 真正的保存
     * 保存草稿
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult submitNews(WmNewsDto dto) throws Exception {
        //1. 校验参数 如果参数不对返回501
        if(null == dto || StringUtils.isEmpty(dto.getContent())){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //2. 保存或者修改文章数据(wm_news)
        WmNews wmNews = saveOrUpdateNews(dto);

        //3. 判断是否是草稿 如果是草稿则直接返回(status状态 提交为1  草稿为0)
        if(dto.getStatus().equals(WmNews.Status.NORMAL)){
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        }

        //4. 从内容中抽取出所有的图片地址
        List<String> imageUrls = ectractContentImageUrl(dto.getContent());

        //5. 保存内容图片和素材之间的关系
        saveRelativeInfoForContent(imageUrls, wmNews.getId());

        //6. 保存封面图片和素材之间的关系(单图 多图 无图 自动(需要根据规则抽取图片))
        saveRelativeInfoForCover(dto, imageUrls, wmNews);

        //7. 异步调用审核进行文章的审核
//        wmNewsAutoScanService.autoScanWmNews(wmNews.getId());;
        //7. 添加审核的任务
        wmNewsTaskService.addWmNewsToTask(wmNews);


        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 封面与素材之间的关系
     * @param dto
     * @param imageUrls
     * @param wmNews
     */
    private void saveRelativeInfoForCover(WmNewsDto dto, List<String> imageUrls, WmNews wmNews) {
        List<String> images = dto.getImages();

        //自动
        if(dto.getType().equals(WemediaConstants.WM_NEWS_TYPE_AUTO)){
            imageUrls = imageUrls.stream().distinct().collect(Collectors.toList());
            if(imageUrls.size() >= 3){
                //多图
                images = imageUrls.stream().limit(3).collect(Collectors.toList());
                wmNews.setType(WemediaConstants.WM_NEWS_MANY_IMAGE);
            }else if(imageUrls.size() >= 1){
                //单图
                images = imageUrls.stream().limit(1).collect(Collectors.toList());
                wmNews.setType(WemediaConstants.WM_COVER_REFERENCE);
            }else{
                //无图
                wmNews.setType(WemediaConstants.WM_CONTENT_REFERENCE);
            }

            //因为修改了文章的类型 所以需要更新
            updateById(wmNews);
        }


        if(null != images && images.size() > 0){
            //保存关系
            images = images.stream().distinct().collect(Collectors.toList());

            List<WmMaterial> wmMaterials = wmMaterialMapper.selectList(Wrappers.<WmMaterial>lambdaQuery().in(WmMaterial::getUrl, images));

            if(null == wmMaterials || images.size() != wmMaterials.size()){
                throw new CustomException(AppHttpCodeEnum.MATERIAL_REFERENCE_FAIL);
            }

            List<Integer> ids = wmMaterials.stream().map(wmMaterial -> wmMaterial.getId()).collect(Collectors.toList());

            wmNewsMaterialMapper.saveRelationInfo(wmNews.getId(), ids, WemediaConstants.COLLECT_MATERIAL);
        }
    }

    /**
     * 保存内容和图片之间的关系
     * @param imageUrls
     * @param id
     */
    private void saveRelativeInfoForContent(List<String> imageUrls, Integer id) {
        //1. 判断是否有图片
        if(null != imageUrls && imageUrls.size() > 0){
            //2. 如果有则先对图片url地址进行去重
            imageUrls = imageUrls.stream().distinct().collect(Collectors.toList());

            //3. 根据url地址查询素材对象
            List<WmMaterial> wmMaterials = wmMaterialMapper.selectList(Wrappers.<WmMaterial>lambdaQuery().in(WmMaterial::getUrl, imageUrls));

            //4. 校验去重以后的url地址的个数和查询到的素材的数量是否相等 如果不相等 表示操作的过程中有其他人删除了素材数据 不能再继续添加了
            if(null == wmMaterials || imageUrls.size() != wmMaterials.size()){
                throw new CustomException(AppHttpCodeEnum.MATERIAL_REFERENCE_FAIL);
            }

            //5. 批量保存内容和素材之间的关系到中间关系表
            List<Integer> ids = wmMaterials.stream().map(wmMaterial -> wmMaterial.getId()).collect(Collectors.toList());

            wmNewsMaterialMapper.saveRelationInfo(id, ids, WemediaConstants.CANCEL_COLLECT_MATERIAL);
        }


    }

    /**
     * 从文章内容中抽取图片地址数据
     * @param content
     * @return
     */
    private List<String> ectractContentImageUrl(String content) {
        List<String> imageUrls = new ArrayList<>();

        List<Map> list = JSON.parseArray(content, Map.class);
        for (Map map : list) {
            if("image".equals(map.get("type"))){
                imageUrls.add(map.get("value").toString());
            }
        }

        return imageUrls;
    }

    /**
     * 新增或者更新
     * @param dto
     * @return
     */
    private WmNews saveOrUpdateNews(WmNewsDto dto) {
        WmNews wmNews = new WmNews();

        BeanUtils.copyProperties(dto, wmNews);

        wmNews.setCreatedTime(new Date());
        wmNews.setEnable((short)1);
        wmNews.setUserId(WmThreadLocalUtil.getUser().getId());

        //处理 图片数据和布局数据
        if(null != dto.getImages() && dto.getImages().size() > 0){
            //[xxx.png,aaa.jpg] -> xxx.png,aaa.jpg
            wmNews.setImages(StringUtils.join(dto.getImages(), ","));
        }

        // 如果是自动 则需要重写type为null
        if(-1 == dto.getType()){
            wmNews.setType(null);
        }

        if(null == dto.getId()){
            //新增数据 - mybatisplus 新增以后会把他的id带回来
            save(wmNews);
        }else{
            //修改
            //删除文章的所有关联数据 - 根据文章的id来删除
            wmNewsMaterialMapper.delete(Wrappers.<WmNewsMaterial>lambdaQuery().eq(WmNewsMaterial::getNewsId, dto.getId()));

            //更新文章的数据
            updateById(wmNews);
        }

        return wmNews;
    }
}
